﻿using System.Linq;
using System.Web.Mvc;

using AMC.SubstitutionCache.Models;
using AMC.SubstitutionCache.Services;
using AMC.SubstitutionCache.ViewModel;

using Orchard;
using Orchard.Caching;
using Orchard.ContentManagement;
using Orchard.Localization;
using Orchard.OutputCache.Models;
using Orchard.OutputCache.Services;
using Orchard.Security;
using Orchard.Settings;
using Orchard.UI.Admin;
using Orchard.UI.Navigation;
using Orchard.UI.Notify;

using CacheItem = AMC.SubstitutionCache.Models.CacheItem;

namespace AMC.SubstitutionCache.Controllers
{
    [Admin]
    public class AdminController : Controller
    {
        private readonly ISubstitutionCacheStorageProvider _cacheStorageProvider;
        private readonly ISiteService _siteService;
        private readonly ISignals _signals;

        public AdminController(
            IOrchardServices services,
            ISubstitutionCacheStorageProvider cacheStorageProvider,
            ISiteService siteService,
            ISignals signals)
        {
            _cacheStorageProvider = cacheStorageProvider;
            _siteService = siteService;
            _signals = signals;

            Services = services;
            T = NullLocalizer.Instance;
        }

        public IOrchardServices Services { get; set; }
        public Localizer T { get; set; }

        public ActionResult Index(PagerParameters pagerParameters)
        {
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not allowed to manage substitution cache")))
                return new HttpUnauthorizedResult();

            var settings = Services.WorkContext.CurrentSite.As<SubstitutionCacheSettingsPart>();
            var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters);

            int totalItemCount;

            var stats = _cacheStorageProvider.GetStatisticsItemViewModel(pager.GetStartIndex(), pager.PageSize, out totalItemCount);

            var pagerShape = Services.New.Pager(pager).TotalItemCount(totalItemCount);
                
            var model = new IndexViewModel
            {
                DoTransformOnRedirect = settings.DoTransformOnRedirect,
                DefaultCacheDurationSeconds = settings.DefaultCacheDurationSeconds,
                ExcludedShapeTypes = settings.ExcludedShapeTypes,
                Statistics = new StatisticsViewModel
                {
                    CacheItems = stats,
                    Pager = pagerShape
                }
            };

            return View(model);
        }

        [HttpPost, ActionName("Index")]
        public ActionResult IndexPost()
        {
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not allowed to manage substitution cache")))
                return new HttpUnauthorizedResult();

            var model = new IndexPostViewModel();

            if (TryUpdateModel(model))
            {
                var settings = Services.WorkContext.CurrentSite.As<SubstitutionCacheSettingsPart>();
                settings.DoTransformOnRedirect = model.DoTransformOnRedirect;
                settings.DefaultCacheDurationSeconds = model.DefaultCacheDurationSeconds;
                settings.ExcludedShapeTypes = model.ExcludedShapeTypes;

                // invalidates the settings cache
                _signals.Trigger(CacheSettingsPart.CacheKey);

                Services.Notifier.Information(T("Substitution Cache Settings saved successfully."));
            }
            else
            {
                Services.Notifier.Error(T("Could not save Substitution Cache Settings."));
            }

            return RedirectToAction("Index");
        }

        public ActionResult Evict(string cacheKey)
        {
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not allowed to manage substitution cache")))
                return new HttpUnauthorizedResult();

            _cacheStorageProvider.Remove(cacheKey);

            Services.Notifier.Information(T("Substitution Cache Item {0} removed successfully.", cacheKey));

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult EvictAll()
        {
            if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not allowed to manage substitution cache")))
                return new HttpUnauthorizedResult();

            _cacheStorageProvider.RemoveAll();

            Services.Notifier.Information(T("All Substitution Cache items removed successfully."));


            return RedirectToAction("Index");
        }
    }
}